//
//  SetTimeTableViewCell.m
//  MedicineBox
//
//  Created by dllo on 15/8/28.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "AlarmTableViewCell.h"
#import "DKNightVersion.h"
#import "SaveTools.h"

@interface AlarmTableViewCell ()

@property (nonatomic, retain) UILabel *nameLabel;
@property (nonatomic, retain) UILabel *timeLabel;
@property (nonatomic, retain) UILabel *markLabel;

@property (nonatomic, retain) NSString *hour;
@property (nonatomic, retain) NSString *minute;

@end

@implementation AlarmTableViewCell

-(void)dealloc
{
    [_markLabel release];
    [_nameLabel release];
    [_timeLabel release];
    [_switchButton release];
    [_hour release];
    [_minute release];
    [super dealloc];
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        [DKNightVersionManager addClassToSet:self.class];
        self.nightBackgroundColor = UIColorFromRGB(0x343434);
        
        self.nameLabel = [[UILabel alloc] init];
        [self.contentView addSubview:self.nameLabel];
        [_nameLabel release];
        
        self.markLabel = [[UILabel alloc] init];
        [self.contentView addSubview:self.markLabel];
        [_markLabel release];
        
        self.timeLabel = [[UILabel alloc] init];
        [self.contentView addSubview:self.timeLabel];
        [_timeLabel release];
        
        self.switchButton = [[UISwitch alloc] init];
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        if (![user boolForKey:@"on"]) {
            self.switchButton.on = NO;
        }else
        {
            self.switchButton.on = YES;
        }
        [self.contentView addSubview:self.switchButton];
        [_switchButton release];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.nameLabel.frame = CGRectMake(15, 10, self.contentView.frame.size.width - 75, 20);
    self.nameLabel.textColor = [UIColor blueColor];
    self.markLabel.frame = CGRectMake(15, self.nameLabel.frame.origin.y + self.nameLabel.frame.size.height + 5, self.nameLabel.frame.size.width, 20);
    self.markLabel.textColor = [UIColor grayColor];
    self.timeLabel.frame = CGRectMake(15, self.markLabel.frame.size.height + self.markLabel.frame.origin.y + 5, self.nameLabel.frame.size.width, 20);
    self.timeLabel.textColor = [UIColor grayColor];
    self.switchButton.frame = CGRectMake(self.contentView.frame.size.width - 80, (self.contentView.frame.size.height - 60) / 2, 60, 30);
    
    [self.switchButton addTarget:self action:@selector(switchButtonAction:) forControlEvents:UIControlEventValueChanged];
    
}

- (void)valueWithDic:(NSDictionary *)dic
{
    self.nameLabel.text = [dic objectForKey:@"name"];
    self.markLabel.text = [NSString stringWithFormat:@"%@  %@",[dic objectForKey:@"people"], [dic objectForKey:@"mark"]];
    self.timeLabel.text = [NSString stringWithFormat:@"%@  %@",[dic objectForKey:@"repeat"], [dic objectForKey:@"time"]];
    self.hour = [dic objectForKey:@"hour"];
    self.minute = [dic objectForKey:@"minute"];

}


#pragma mark -
#pragma mark 通知本地消息
- (void)switchButtonAction:(UISwitch *)switchButton
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:(@"yyyy-MM-dd HH:mm:ss")];
    NSString *now = [formatter stringFromDate:[NSDate new]];
    NSString *fireTimeStr = [NSString stringWithFormat:@"%@%@:%@:00",[now substringToIndex:11],self.hour,self.minute];
    NSDate *fireTime = [formatter dateFromString:fireTimeStr];
    
    if (switchButton.isOn) {
        NSString *path = [SaveTools pathWithName:@"on" directory:NSDocumentDirectory];
        NSString *str = @"on";
        [str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"%@",path);
        [AlarmTableViewCell registerLocalNotification:fireTime];
        
    }else
    {
        NSString *path = [SaveTools pathWithName:@"on" directory:NSDocumentDirectory];
        NSFileManager *manager = [NSFileManager defaultManager];
        if ([manager fileExistsAtPath:path]) {
            [manager removeItemAtPath:path error:nil];
        }
        [AlarmTableViewCell cancelLocalNotificationWithKey:@"key"];
    }
    
}

// 设置本地通知
+ (void)registerLocalNotification:(NSDate *)alertTime {
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    // 设置触发通知的时间
    NSLog(@"%@", alertTime);
    notification.fireDate = alertTime;
    // 时区
    notification.timeZone = [NSTimeZone defaultTimeZone];
    // 设置重复的间隔
    notification.repeatInterval = kCFCalendarUnitSecond;
    // 通知内容
    notification.alertBody =  @"到点了吃药";
    notification.applicationIconBadgeNumber = 1;
    // 通知被触发时播放的声音
    notification.soundName = UILocalNotificationDefaultSoundName;
    // 通知参数
    NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"开始吃药了" forKey:@"key"];
    notification.userInfo = userDict;
    
    // ios8后，需要添加这个注册，才能得到授权
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        // 通知重复提示的单位，可以是天、周、月
        notification.repeatInterval = NSCalendarUnitDay;
    } else {
        // 通知重复提示的单位，可以是天、周、月
        notification.repeatInterval = NSCalendarUnitDay;
    }
    
    // 执行通知注册
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

// 取消某个本地推送通知
+ (void)cancelLocalNotificationWithKey:(NSString *)key {
    // 获取所有本地通知数组
    NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
    
    for (UILocalNotification *notification in localNotifications) {
        NSDictionary *userInfo = notification.userInfo;
        if (userInfo) {
            // 根据设置通知参数时指定的key来获取通知参数
            NSString *info = userInfo[key];
            
            // 如果找到需要取消的通知，则取消
            if (info != nil) {
                [[UIApplication sharedApplication] cancelLocalNotification:notification];
                break;
            }
        }
    }
}


- (void)awakeFromNib {
    
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    
}

@end
